package com.dylan.job.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;

/**
 * @author dylan
 * @description 网络工具类
 * @date 2025/2/11  22:12
 */
@Slf4j
public class NetUtil {

    public static int findAvailablePort(int defaultPort) {
        int portTmp = defaultPort;
        //先向上查找
        while (portTmp < 65535) {
            if (!isPortUsed(portTmp)) { //如果port没被使用则返回该port
                return portTmp;
            } else {
                portTmp++;
            }
        }
        portTmp = defaultPort--;
        while (portTmp > 0) {
            if (!isPortUsed(portTmp)) {
                return portTmp;
            } else {
                portTmp--;
            }
        }
        //直接抛出异常,没有可用的port
        throw new RuntimeException("no available port.");
    }

    private static boolean isPortUsed(int portTmp) {
        boolean used = false;
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(portTmp);

        } catch (IOException e) {
            used = true;
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    log.info("ServerSocket close error");
                }
            }
        }

        return used;
    }
}
